<template>
    <div class="edit-profile-page">
        <van-nav-bar title="Edit Profile" left-text="Back" left-arrow @click-left="$router.back()">
            <template #right>
                <van-button type="primary" size="small" @click="saveProfile">
                    Save
                </van-button>
            </template>
        </van-nav-bar>

        <div class="edit-content">
            <!-- Avatar Section -->
            <div class="avatar-section">
                <div class="avatar-container">
                    <img :src="profileData.avatar" alt="Avatar" class="avatar" />
                    <div class="avatar-overlay" @click="changeAvatar">
                        <van-icon name="camera-o" size="24" color="white" />
                    </div>
                </div>
                <div class="avatar-text">Tap to change photo</div>
            </div>

            <!-- Profile Form -->
            <van-form @submit="saveProfile">
                <van-cell-group inset>
                    <van-field v-model="profileData.username" name="username" label="Username"
                        placeholder="Enter username" :rules="[{ required: true, message: 'Username is required' }]" />
                    <van-field v-model="profileData.displayName" name="displayName" label="Display Name"
                        placeholder="Enter display name" />
                    <van-field v-model="profileData.email" name="email" label="Email" placeholder="Enter email"
                        type="email" :rules="[{ required: true, message: 'Email is required' }]" />
                    <van-field v-model="profileData.bio" name="bio" label="Bio" placeholder="Tell us about yourself"
                        type="textarea" rows="3" maxlength="200" show-word-limit />
                </van-cell-group>

                <van-cell-group inset title="Personal Information">
                    <van-field v-model="profileData.location" name="location" label="Location"
                        placeholder="Enter your location" />
                    <van-field v-model="profileData.website" name="website" label="Website"
                        placeholder="Enter your website" type="url" />
                    <van-field v-model="profileData.linkedin" name="linkedin" label="LinkedIn"
                        placeholder="LinkedIn profile URL" />
                </van-cell-group>

                <van-cell-group inset title="Preferences">
                    <van-field name="language" label="Language">
                        <template #input>
                            <van-picker v-model="selectedLanguage" :columns="languageOptions"
                                @confirm="onLanguageConfirm" />
                        </template>
                    </van-field>
                    <van-field name="notifications" label="Email Notifications">
                        <template #input>
                            <van-switch v-model="profileData.emailNotifications" />
                        </template>
                    </van-field>
                    <van-field name="privacy" label="Profile Visibility">
                        <template #input>
                            <van-picker v-model="selectedPrivacy" :columns="privacyOptions"
                                @confirm="onPrivacyConfirm" />
                        </template>
                    </van-field>
                </van-cell-group>
            </van-form>
        </div>

        <!-- Image Picker -->
        <van-action-sheet v-model:show="showImagePicker" :actions="imageActions" @select="onImageActionSelect"
            cancel-text="Cancel" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showImagePreview } from 'vant'
import { userApi } from '@/api/user'

const router = useRouter()

const profileData = reactive({
    avatar: '/api/placeholder/120/120',
    username: 'john_doe',
    displayName: 'John Doe',
    email: 'john.doe@example.com',
    bio: 'Passionate about improving social skills and helping others grow.',
    location: 'San Francisco, CA',
    website: 'https://johndoe.com',
    linkedin: 'https://linkedin.com/in/johndoe',
    language: 'English',
    emailNotifications: true,
    profileVisibility: 'Public'
})

const showImagePicker = ref(false)
const selectedLanguage = ref(['English'])
const selectedPrivacy = ref(['Public'])

const languageOptions = [
    { text: 'English', value: 'en' },
    { text: '中文', value: 'zh' },
    { text: 'Español', value: 'es' },
    { text: 'Français', value: 'fr' },
    { text: 'Deutsch', value: 'de' }
]

const privacyOptions = [
    { text: 'Public', value: 'public' },
    { text: 'Friends Only', value: 'friends' },
    { text: 'Private', value: 'private' }
]

const imageActions = [
    { name: 'Take Photo', value: 'camera' },
    { name: 'Choose from Gallery', value: 'gallery' },
    { name: 'View Current Photo', value: 'view' }
]

const changeAvatar = () => {
    showImagePicker.value = true
}

const onImageActionSelect = async (action: any) => {
    showImagePicker.value = false

    switch (action.value) {
        case 'camera':
            await takePhoto()
            break
        case 'gallery':
            await selectFromGallery()
            break
        case 'view':
            showImagePreview([profileData.avatar])
            break
    }
}

const takePhoto = async () => {
    try {
        showToast('Camera feature not available in demo')
        // In a real app, this would use camera API
    } catch (error) {
        showToast('Failed to access camera')
    }
}

const selectFromGallery = async () => {
    try {
        const input = document.createElement('input')
        input.type = 'file'
        input.accept = 'image/*'

        input.onchange = async (event) => {
            const file = (event.target as HTMLInputElement).files?.[0]
            if (file) {
                await uploadAvatar(file)
            }
        }

        input.click()
    } catch (error) {
        showToast('Failed to select image')
    }
}

const uploadAvatar = async (file: File) => {
    try {
        // Validate file
        if (file.size > 5 * 1024 * 1024) {
            showToast('Image size must be less than 5MB')
            return
        }

        if (!file.type.startsWith('image/')) {
            showToast('Please select a valid image file')
            return
        }

        // Create preview
        const reader = new FileReader()
        reader.onload = (e) => {
            profileData.avatar = e.target?.result as string
            showToast('Avatar updated! Remember to save your changes.')
        }
        reader.readAsDataURL(file)

    } catch (error) {
        showToast('Failed to upload avatar')
    }
}

const onLanguageConfirm = (value: any) => {
    profileData.language = value.text
}

const onPrivacyConfirm = (value: any) => {
    profileData.profileVisibility = value.text
}

const saveProfile = async () => {
    try {
        // Update profile via API
        const response = await userApi.updateProfile({
            username: profileData.username,
            bio: profileData.bio
        })

        if (response.success) {
            showToast('Profile updated successfully!')
            router.back()
        } else {
            throw new Error(response.error || 'Update failed')
        }
    } catch (error) {
        console.error('Profile update error:', error)
        showToast('Failed to update profile')
    }
}
</script>

<style lang="scss" scoped>
.edit-profile-page {
    min-height: 100vh;
    background: #f8f9fa;
}

.edit-content {
    padding: 16px;
}

.avatar-section {
    text-align: center;
    margin-bottom: 24px;

    .avatar-container {
        position: relative;
        display: inline-block;
        margin-bottom: 8px;

        .avatar {
            width: 120px;
            height: 120px;
            border-radius: 60px;
            object-fit: cover;
        }

        .avatar-overlay {
            position: absolute;
            bottom: 0;
            right: 0;
            width: 36px;
            height: 36px;
            background: #1989fa;
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border: 3px solid white;
        }
    }

    .avatar-text {
        font-size: 14px;
        color: #969799;
    }
}

:deep(.van-cell-group) {
    margin-bottom: 16px;
}

:deep(.van-cell-group__title) {
    padding: 16px 16px 8px;
    font-size: 14px;
    font-weight: 500;
    color: #323233;
}
</style>